package system_service

import (
	"errors"
	"time"

	"github.com/APP/global"
	"github.com/APP/internal/models"
	"github.com/APP/internal/utils"
	"gorm.io/gorm"
)

type UserService struct{}

// Register 用户注册
func (userService *UserService) Register(user *models.User) (*models.User, error) {
	var existUser models.User
	if !errors.Is(global.APP_DB.Where("username = ?", user.Username).First(&existUser).Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("用户名已存在")
	}
	if user.Email != "" {
		if !errors.Is(global.APP_DB.Where("email = ?", user.Email).First(&existUser).Error, gorm.ErrRecordNotFound) {
			return nil, errors.New("邮箱已存在")
		}
	}

	// 密码加密
	hashedPassword, err := utils.BcryptHash(user.Password)
	if err != nil {
		return nil, err
	}
	user.Password = hashedPassword

	err = global.APP_DB.Create(user).Error
	if err != nil {
		return nil, err
	}

	return user, nil
}

// Login 用户登录
func (userService *UserService) Login(username, password string) (*models.User, error) {
	var user models.User
	if global.APP_DB == nil {
		return nil, errors.New("数据库连接未初始化")
	}
	err := global.APP_DB.Where("username = ? AND status = ?", username, 1).First(&user).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("用户不存在或已被禁用")
		}
		return nil, err
	}

	// 验证密码
	if !utils.BcryptCheck(password, user.Password) {
		return nil, errors.New("密码错误")
	}

	// 更新最后登录时间
	now := time.Now()
	user.LastLoginAt = &now
	global.APP_DB.Save(&user)

	return &user, nil
}

// GetUserInfo 获取用户信息
func (userService *UserService) GetUserInfo(userID int64) (*models.User, error) {
	var user models.User
	err := global.APP_DB.Preload("Roles").Where("id = ?", userID).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// UpdateUser 更新用户信息
func (userService *UserService) UpdateUser(user *models.User) error {
	return global.APP_DB.Save(user).Error
}

// ChangePassword 修改密码
func (userService *UserService) ChangePassword(userID int64, oldPassword, newPassword string) error {
	var user models.User
	err := global.APP_DB.Where("id = ?", userID).First(&user).Error
	if err != nil {
		return err
	}

	// 验证旧密码
	if !utils.BcryptCheck(oldPassword, user.Password) {
		return errors.New("原密码错误")
	}

	// 加密新密码
	hashedPassword, err := utils.BcryptHash(newPassword)
	if err != nil {
		return err
	}

	user.Password = hashedPassword
	return global.APP_DB.Save(&user).Error
}

// GetUserList 获取用户列表
func (userService *UserService) GetUserList(page, pageSize int) ([]models.User, int64, error) {
	var users []models.User
	var total int64

	db := global.APP_DB.Model(&models.User{})

	err := db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	offset := (page - 1) * pageSize
	err = db.Preload("Roles").Offset(offset).Limit(pageSize).Find(&users).Error
	if err != nil {
		return nil, 0, err
	}

	return users, total, nil
}

// DeleteUser 删除用户
func (userService *UserService) DeleteUser(userID int64) error {
	return global.APP_DB.Delete(&models.User{}, userID).Error
}
